<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
          @select-clear="clearOrg"
        />
      </el-form-item>
      <el-form-item :table-form-merge="0.2">
        <el-checkbox v-model="query.option" label="包含下级" />
      </el-form-item>
      <el-form-item label="排班年月:">
        <el-date-picker
          v-model="query.yearMonth"
          type="month"
          placeholder="选择月"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[50401,1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
        <el-button
          v-permission="[50401,4]"
          type="primary"
          icon="el-icon-download"
          :loading="$loadingPlugin.exportFile"
          @click="exportFile"
        >导出</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      :height="tableHeight"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      :cell-class-name="cellClassName"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      :immediate-fetch="false"
      @fetch="fetchData"
      @cell-click="cellClick"
    />
    <div v-show="showBtn" class="btns-dialog">
      <i class="el-icon-close btn-close" @click="() => showBtn = false" />
      <div v-permission="[50401,2]" class="btn blue" @click="handleSingle">班</div>
      <div v-permission="[50401,3]" class="btn red" @click="handleClear">清空</div>
    </div>
    <single ref="single" :parent-fetch-data="refresh" />
    <batch ref="batch" :parent-fetch-data="refresh" />
  </div>
</template>

  <script>
  import { fenceSchedulingList, queryAllUserByOrgSNNo, fenceSchedulingClear, queryExportDomain, exportForPs } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { mapGetters } from 'vuex'
  import single from './single.vue'
  import batch from './batch.vue'
  export default {
    name: 'distribution',
    components: { single, batch },
    data() {
      return {
        tableHeight: '50',
        query: {
          orgSNNo: '',
          yearMonth: new Date(),
          option: false
        },
        yearMonth: '',
        treeData: [],
        tableData: {
          data: []
        },
        currentRowIndex: '',
        currentcolumnIndex: '',
        showBtn: false
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData', 'userInfo']),
      days() {
        return this.getMonthDays(this.yearMonth)
      },
      column() {
        const column = [
          {
            prop: 'orgName',
            label: '站点',
            width: 130,
            fixed: 'left',
            showOverflowTooltip: true
          },
          {
            prop: 'fenceName',
            label: '配送员围栏',
            width: 150,
            fixed: 'left',
            showOverflowTooltip: true
          },
          {
            label: '操作',
            fixed: 'right',
            width: 85,
            render: (h, { row, $index }) => {
              return (
                  <div>
                    <el-link v-permission={[50401, 5]} underline={false} size='mini' onClick={() => this.handleBatch(row, $index)}>
                      批量排班
                    </el-link>
                  </div>
                )
            }
          }
        ]
        for (let i = 1; i <= this.days; i++) {
          const columnObj = {
            prop: 'day' + i.toString() + 'name',
            label: i.toString(),
            width: 100,
            showOverflowTooltip: true
          }
          column.splice(i + 2, 0, columnObj)
        }
        return column
      }
    },
    async created() {
      this.getTreeData()
      this.getExportDomain()
      await this.getUserOrder()
      this.search()
      this.getHeight()
      window.addEventListener('resize', this.getHeight)
    },
    methods: {
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.orgId = value.orgId
        this.query.orgName = value.orgName
      },
      clearOrg() {
        this.query.orgId = ''
        this.query.orgSNNo = ''
      },
      getHeight() {
        this.$nextTick(() => {
          this.tableHeight = document.getElementsByClassName('app-page')[0].offsetHeight - 155 + ''
        })
      },
      // 获取月有多少天
      getMonthDays(date) {
        const d = new Date(date)
        d.setMonth(d.getMonth() + 1)
        d.setDate('1')
        d.setDate(d.getDate() - 1)
        return d.getDate()
      },
      // 小于当前日期设置禁止点击修改
      disableColunm() {
        const today = parseTime(new Date(), '{dd}')
        const nowYear = new Date().getFullYear()
        const nowMonth = new Date().getMonth() + 1
        const queryYear = this.query.yearMonth.split('-')[0]
        const queryMonth = this.query.yearMonth.split('-')[1]
        if (parseInt(queryYear) < parseInt(nowYear) || (parseInt(queryYear) === parseInt(nowYear) && parseInt(queryMonth) < parseInt(nowMonth))) {
          for (let i = 0; i < this.days; i++) {
            const doms = document.getElementsByClassName('el-table_1_column_' + parseInt(i + 4))
            for (let i = 1; i < doms.length; i++) {
              doms[i].style.cursor = 'not-allowed'
              doms[i].style.color = '#DCDCDC'
            }
          }
        } else if (parseInt(queryYear) === parseInt(nowYear) && parseInt(queryMonth) === parseInt(nowMonth)) {
          for (let i = 0; i < this.days; i++) {
            if (parseInt(i + 1) < parseInt(today)) {
              const doms = document.getElementsByClassName('el-table_1_column_' + parseInt(i + 4))
              for (let i = 1; i < doms.length; i++) {
                doms[i].style.cursor = 'not-allowed'
                doms[i].style.color = '#DCDCDC'
              }
            } else {
              const doms = document.getElementsByClassName('el-table_1_column_' + parseInt(i + 4))
              for (let i = 1; i < doms.length; i++) {
                doms[i].style.cursor = 'default'
                doms[i].style.color = '#606266'
              }
            }
          }
        } else if ((parseInt(queryYear) === parseInt(nowYear) && parseInt(queryMonth) > parseInt(nowMonth)) || parseInt(queryYear) > parseInt(nowYear)) {
          for (let i = 0; i < this.days; i++) {
            const doms = document.getElementsByClassName('el-table_1_column_' + parseInt(i + 4))
            for (let i = 1; i < doms.length; i++) {
              doms[i].style.cursor = 'default'
              doms[i].style.color = '#606266'
            }
          }
        }
      },
      cellClassName({ row, column, rowIndex, columnIndex }) {
        row.index = rowIndex
        column.index = columnIndex
        const today = parseTime(new Date(), '{dd}')
        const nowYear = new Date().getFullYear()
        const nowMonth = new Date().getMonth() + 1
        const queryYear = this.query.yearMonth.split('-')[0]
        const queryMonth = this.query.yearMonth.split('-')[1]
        if (parseInt(queryYear) < parseInt(nowYear) || (parseInt(queryYear) === parseInt(nowYear) && parseInt(queryMonth) < parseInt(nowMonth))) {
          if (columnIndex > 1) {
            return 'not-allow'
          }
        } else if (parseInt(queryYear) === parseInt(nowYear) && parseInt(queryMonth) === parseInt(nowMonth)) {
          if (columnIndex > 1 && parseInt(columnIndex - 1) < parseInt(today)) {
            return 'not-allow'
          } else {
            return ''
          }
        } else if ((parseInt(queryYear) === parseInt(nowYear) && parseInt(queryMonth) > parseInt(nowMonth)) || parseInt(queryYear) > parseInt(nowYear)) {
          if (columnIndex > 1) {
            return ''
          }
        }
      },
      cellClick(row, column, cell, event) {
        this.currentDay = parseInt(column.index - 1)
        this.currentUser = this.tableData.data[row.index]['day' + this.currentDay]
        this.currentRowIndex = row.index
        console.log(this.currentRowIndex)
        this.currentRow = row
        const scrollLeft = document.getElementsByClassName('el-table__body-wrapper')[0].scrollLeft
        const scrollTop = document.getElementsByClassName('el-table__body-wrapper')[0].scrollTop
        if (cell.className.indexOf('not-allow') === -1) {
          if (column.index > 1 && column.index < this.column.length - 1) {
            this.showBtn = true
            const dom = document.getElementsByClassName('btns-dialog')[0]
            dom.style.top = parseInt(cell.offsetTop - scrollTop + 120) + 'px'
            dom.style.left = parseInt(cell.offsetLeft - scrollLeft) + 'px'
          } else {
            this.showBtn = false
          }
          if (parseInt(column.index) >= 2) {
            if (this.currentNode) {
              this.currentNode.style.background = ''
            }
            if (event.target.nodeName === 'SPAN') {
              this.currentNode = event.target.parentNode.parentNode
            } else if (event.target.nodeName === 'DIV') {
              this.currentNode = event.target.parentNode
            } else {
              this.currentNode = event.target
            }
            this.currentNode.style.setProperty('background-color', '#e6f5f5', 'important')
          }
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgId = this.userInfo.orgId
        this.query.orgSNNo = this.userInfo.orgSNNo
      },
      // 获取所有配送员人员
      async getUserOrder() {
        const params = {
          orgSNNo: ''
        }
        const res = await queryAllUserByOrgSNNo(params)
        this.userOption = res.data
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          orgId: this.query.option ? 0 : this.query.orgId,
          orgSNNo: this.query.orgSNNo,
          schedulingTime: this.query.yearMonth + '-01',
          currentPage,
          pageSize
        }
        const res = await fenceSchedulingList(query)
        this.tableData.data = res.data.rows
        this.tableData.data.forEach((item, index) => {
          for (const key in item) {
            if (key.indexOf('day') > -1) {
              const names = item[key].split(',')
              names.forEach((userId, index2) => {
                names[index2] = formatColumnMap(this.userOption, 'userId', parseInt(userId), 'userName')
              })
              this.tableData.data[index][key + 'name'] = names.join(',')
            }
          }
        })
        this.searchParams = query
        this.tableData.total = res.data.total
      },
      search() {
        this.query.yearMonth = parseTime(this.query.yearMonth, '{yy}-{mm}')
        this.yearMonth = this.query.yearMonth
        this.showBtn = false
        if (this.currentNode) {
          this.currentNode.style.background = ''
        }
        this.$nextTick(() => {
          this.$refs.lbTable.fetch({ currentPage: 1 })
          this.$refs.lbTable.doLayout()
        })
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 单个排班
      handleSingle() {
        const date = this.currentDay < 10 ? this.query.yearMonth + '-' + '0' + this.currentDay.toString() : this.query.yearMonth + '-' + this.currentDay
        this.$refs.single.open({ currentRow: this.currentRow, currentDay: date, currentUser: this.currentUser })
        this.showBtn = false
      },
      // 清空
      handleClear() {
        this.$confirm('确认清空所选日期的排班吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const date = this.currentDay < 10 ? this.query.yearMonth + '-' + '0' + this.currentDay.toString() : this.query.yearMonth + '-' + this.currentDay
          const params = {
            fenceId: this.currentRow.fenceId,
            orgId: this.currentRow.orgId,
            schedulingTime: date
          }
          fenceSchedulingClear(params).then(res => {
            if (res.data) {
              this.$message.success('清空成功！')
              this.showBtn = false
              this.refresh()
            }
          })
        }).catch(() => {

        })
      },
      // 批量排班
      handleBatch(row) {
        this.$refs.batch.open({ days: this.days, yearMonth: this.query.yearMonth, currentRow: row })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 导出
      async exportFile() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          exportForPs({
            paramInfo: this.searchParams
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
  </script>

  <style lang="scss" scoped>
    .btns-dialog {
      position: absolute;
      top: 200px;
      left: 200px;
      z-index: 999;
      padding: 15px 19px 5px;
      background-color: white;
      border: 1px solid #DCDFE6;
      border-radius: 5px;
      .btn {
        width: 60px;
        height: 30px;
        margin-bottom: 10px;
        font-size: 16px;
        font-weight: 600;
        line-height: 30px;
        color: white;
        text-align: center;
        cursor: pointer;
        border-radius: 10px;
      }
      .blue {
        background-color: #0552E6;
      }
      .red {
        background-color: #EE0909;
      }
      .btn-close {
        position: absolute;
        top: 4px;
        left: 78px;
        cursor: pointer;
      }
    }
    /deep/.el-table .el-table__body tr.current-row > td {
      background-color: white !important;
    }
    /deep/.el-table.el-table--striped .el-table__body tr.el-table__row--striped.current-row td,
    .el-table .el-table__body tr.current-row > td {
      background-color: white !important;
    }
    /deep/.not-allow {
      color: #DCDCDC !important;
      cursor: not-allowed;
    }
  </style>

